package cn.jiedh.app.meiweidk.mine;


import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.db.Dbutils;
import cn.jiedh.app.meiweidk.Utils.event.Constant;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.event.Observers;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseFragment;
import cn.jiedh.app.meiweidk.browse.BrowseActivity;
import cn.jiedh.app.meiweidk.browse.QuessionActivity;
import cn.jiedh.app.meiweidk.entity.MsgInfoBean;
import cn.jiedh.app.meiweidk.entity.MsgListBean;
import cn.jiedh.app.meiweidk.homepage.GreenLandActivity;
import cn.jiedh.app.meiweidk.homepage.NewProductData;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.msg.MsgActivity;
import cn.jiedh.app.meiweidk.network.GlideCircleTransform;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionHelper;
import cn.jiedh.app.meiweidk.web.webhandle.ShareBean;
import cn.jiedh.app.meiweidk.welcome.SwitchStauts;

/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentMy extends BaseFragment implements Observers {
    private static final int PERMISSION_SHARE = 8;//分享请求权限的code
    @BindView(R.id.login_tv)
    TextView loginTv;
    @BindView(R.id.is_new_msg)
    ImageView isNewMsgImg;
    Unbinder unbinder;
    @BindView(R.id.user_logo)
    ImageView userLogo;

    @BindView(R.id.username_tv)
            TextView username_tv;

    @BindView(R.id.personal_edu)
        LinearLayout personal_edu;

    ShareBean mShareBean;
    private List<MsgInfoBean> msgList = new ArrayList<>();//
    private Dbutils dbutils;

    @BindView(R.id.editAuthen_tv)
    TextView editAuthen_tv;

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_my;

    }

    @Override
    protected void initView(View view) {
        EventUtils.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventUtils.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (SPUtils.getIsLogin()) {
            String phone = SPUtils.getPhone();
            String maskNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            loginTv.setText("电话 : " + maskNumber);
        } else {
            SpannableString spannableString = new SpannableString("您还未登录，点击立马登录");
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#f11d1c"));
            spannableString.setSpan(colorSpan, 8, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            loginTv.setText(spannableString);
            userLogo.setImageResource(R.mipmap.wd_tx);
            isNewMsgImg.setVisibility(View.GONE);
            username_tv.setText("您好!");
        }
        MobclickAgent.onResume(getActivity());
        getPersonData();
        authMateSwitchs();
    }

    /**
     * 获取用户信息
     */
    private void getPersonData() {
        Map<String, Object> args = new HashMap<>();
        args.put("phone", SPUtils.getPhone());
        request(UrlUtils.GET_PERSONAL_INFO, args, true, new ResponseSuccess<PersonInfo>() {
            @Override
            public void onRequestSucceed(BaseResponse<PersonInfo> response) {
                PersonInfo infor = response.getData();
//                if (response.isSuccess()) {
                username_tv.setText(infor.getUsername());
                if (!TextUtils.isEmpty(infor.getUserImgUrl())) {
                    LoadUtils.loadImage(getActivity(), infor.getUserImgUrl(), userLogo);

                }
//                }
            }
        }, (error, msg) -> {
            T.showShortToast(msg);
        });
    }

    /**
     * 是否开启新人专享开关接口
     */
    public void authMateSwitchs() {
        Map<String, Object> map = new HashMap<>();
        request(UrlUtils.authMateSwitchs, map, true, new ResponseSuccess<SwitchStauts>() {
            @Override
            public void onRequestSucceed(BaseResponse<SwitchStauts> response) {
                if (response.getCode() == 0) {
                    personal_edu.setVisibility(View.VISIBLE);
                } else {
                    personal_edu.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                personal_edu.setVisibility(View.GONE);
            }
        });
    }


    @Override
    protected void initData() {
        if (SPUtils.getIsLogin()) {
            dbutils = new Dbutils();
        }
        getMsgNum();
    }

    public void getMsgNum() {
        Map map = new HashMap<String, Objects>();
        map.put("type", 2);//0系统消息，1活动消息 2全部的消息ID
        request(UrlUtils.MSGID, map, false, new ResponseSuccess<MsgListBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<MsgListBean> response) {
                if (response.getCode() == 0) {
                    msgList.clear();
                    msgList.addAll(response.getData().getDataList());
                    if (msgList != null && msgList.size() > 0) {
                        if (saveIDs(msgList)) {
                            //有新消息
                            isNewMsgImg.setVisibility(View.VISIBLE);
                        } else {
                            isNewMsgImg.setVisibility(View.GONE);
                        }
                    }
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化banner错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    Map<String, String> mmp = new HashMap<>();

    @OnClick({R.id.personal_edu, R.id.browse, R.id.problem, R.id.cooperation, R.id.setting,
            R.id.share, R.id.login_tv, R.id.msg_btn, R.id.personal_data, R.id.chat_center, R.id.info_top, R.id.user_logo
    ,R.id.editAuthen_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.browse:
                if (SPUtils.getIsLogin()) {
                    MobclickAgent.onEvent(getActivity(), "my_browse_click");
                    SPUtils.saveBuried("click", "0", "我的浏览点击", "",
                            "我的", "", "", "");
                    ActivityUtil.next(getActivity(), BrowseActivity.class);
                    collect("6",null,null);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);
                }
                break;
            case R.id.problem:
                MobclickAgent.onEvent(getActivity(), "my_help_click");
                MobclickAgent.onEvent(getActivity(), "quesstion"); //umeng
                ActivityUtil.next(getActivity(), QuessionActivity.class);
                SPUtils.saveBuried("click", "0", "帮助中心点击", "",
                        "我的", "", "", "");
                break;
            case R.id.cooperation:
                MobclickAgent.onEvent(getActivity(), "my_corperation_click");
                ActivityUtil.next(getActivity(), CooperationActivity.class);
                SPUtils.saveBuried("click", "0", "商务合作点击", "",
                        "我的", "", "", "");
                break;
            case R.id.setting:
                if (!SPUtils.getIsLogin()) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);
                } else {
                    MobclickAgent.onEvent(getActivity(), "my_setting_click");
                    ActivityUtil.next(getActivity(), SettingActivity.class);
                    SPUtils.saveBuried("click", "0", "设置点击", "",
                            "我的", "", "", "");
                }
//                WebActivity.launch("http://192.168.0.195:8080/bridge.html",null,getActivity());
                break;
            case R.id.share:
                MobclickAgent.onEvent(getActivity(), "my_share_click");
                MobclickAgent.onEvent(getActivity(), "invite"); //umeng
                SPUtils.saveBuried("click", "0", "邀请朋友分享点击", "",
                        "我的", "", "", "");
//                Bundle b = new Bundle();
//                BannerEntity bannerEntity = new BannerEntity();
//                bannerEntity.setShareLink(SPUtils.getAppInfoFromSP().getShareLink());
//                bannerEntity.setShareImgUrl(SPUtils.getAppInfoFromSP().getShareImgUrl());
//                bannerEntity.setShareTitle(SPUtils.getAppInfoFromSP().getShareTitle());
//                bannerEntity.setShareContent(SPUtils.getAppInfoFromSP().getShareContent());
//                b.putSerializable("Hot", bannerEntity);
//                b.putBoolean("isInvite", true);
//                ActivityUtil.next(getActivity(), MyShareActivity.class, b);

                mShareBean = new ShareBean(SPUtils.getAppInfoFromSP().getShareLink(), SPUtils.getAppInfoFromSP().getShareTitle(), SPUtils.getAppInfoFromSP().getShareContent(), SPUtils.getAppInfoFromSP().getShareImgUrl());

                String[] mPermissionList = new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CALL_PHONE,
//                    Manifest.permission.READ_LOGS,
//                    Manifest.permission.READ_PHONE_STATE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.SET_DEBUG_APP,
//                    Manifest.permission.SYSTEM_ALERT_WINDOW,
//                    Manifest.permission.GET_ACCOUNTS,
//                    Manifest.permission.WRITE_APN_SETTINGS
                };
                PermissionHelper.requestMultiPermissions(getActivity(), this, PERMISSION_SHARE, "分享需要权限《存储》，请授权", permissionResult, mPermissionList);
                break;
            case R.id.login_tv:
            case R.id.info_top:
            case R.id.user_logo:
                if (!SPUtils.getIsLogin()) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);
                } else {
                    ActivityUtil.next(getActivity(), PersonalDataActivity.class);
                }
                break;
            case R.id.msg_btn:
                if (!SPUtils.getIsLogin()) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);
                } else {
                    isNewMsgImg.setVisibility(View.GONE);
                    ActivityUtil.next(getActivity(), MsgActivity.class);
                }
                break;
            case R.id.personal_data:
                if (SPUtils.getIsLogin()) {
                    MobclickAgent.onEvent(getActivity(), "my_profile_click");
                    ActivityUtil.next(getActivity(), PersonalDataActivity.class);
                    SPUtils.saveBuried("click", "0", "个人资料点击", "",
                            "我的", "", "", "");
                } else {
                    T.showShort("请先登录");
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);

                }
                break;
            case R.id.chat_center:
                MobclickAgent.onEvent(getActivity(), "my_service_click");
                ActivityUtil.next(getActivity(), NewChatActivity.class);
                SPUtils.saveBuried("click", "0", "助贷服务点击", "",
                        "我的", "", "", "");
                break;

            case R.id.personal_edu:
                if (SPUtils.getIsLogin()) {
                    MobclickAgent.onEvent(getActivity(), "Myquota");
                    sendGetData();
                    collect("7",null,null);
                } else {
                    T.showShort("请先登录");
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(getActivity(), LoginActivity.class, bundle);
                }
                break;

            case R.id.editAuthen_tv:
                ActivityUtil.next(getActivity(), AuthenActivity.class);
                break;
            default:
                break;
        }
    }


    /**
     * 获取当前用户认证信息
     */
    private void sendGetData() {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();

        request(UrlUtils.GREEN_LAND_DATA, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                dismissLoadingDialog();
                if (response.getCode() == 0) {//个人资料已完善

                    MobclickAgent.onEvent(getActivity(), "my_quota_click");
                    SPUtils.saveBuried("click", "0", "我的额度点击", "",
                            "我的", "", "", "");
                    ActivityUtil.next(getActivity(), MyQuotaActivity.class);

                } else {//个人资料未完善 跳转到完善个人资料
                    AlertDialog dialog = new AlertDialog(getActivity()).builder();

                    dialog.setMsg("您还未实名认证，请先通过实名认证").setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ActivityUtil.next(getActivity(), AuthenActivity.class);
                        }
                    }).show();


                }

            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                dismissLoadingDialog();
//                tips_tv.setText("0");
            }
        });
    }



    /**
     * 进入消息页面，获取messageid并保存数据库
     *
     * @param allIDs 所有消息ID
     */
    boolean saveIDs(List<MsgInfoBean> allIDs) {
        //１查询数据库表是否存在，若没有数据，创建数据库表，加入所有状态为1；
        //2 若有数据，加入新增数据，加入状态为0；
        boolean hasNew = false;
        if (SPUtils.getIntoMessageListState()) {
            L.e("未创建表");
            dbutils.dropTable();
            SPUtils.setIntoMessageListState();
            //保存初始消息ID并设置为已读
            MsgInfoBean messageBean = new MsgInfoBean();
            for (int i = 0; i < allIDs.size(); i++) {
                messageBean.setState("1");//已读
                messageBean.setId(allIDs.get(i).getMessageId() + "");
                dbutils.SaveMessage(messageBean);
                hasNew = true;
            }
            L.d("未创建表", dbutils.Getallmessage().size() + "");
        } else {
            L.e("已创建表");
            int exsit = 0;//已存在消息数量
            List<MsgInfoBean> dbList = dbutils.Getallmessage();
            if (dbList != null) {
                exsit = dbList.size();
                L.d("====>" + exsit);
            }
            //保存新的消息ID并设置为未读
            MsgInfoBean messageBean = new MsgInfoBean();
            for (int i = 0; i < allIDs.size() - exsit; i++) {
                messageBean.setId(allIDs.get(i).getMessageId() + "");
                messageBean.setState("0");//未读
                dbutils.SaveMessage(messageBean);
                hasNew = true;
            }
            L.d("已创建表", dbutils.Getallmessage().size() + "");
        }
        return hasNew;
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
    }

    @Override
    public void update(Object obj) {
        if ((obj instanceof EventScreen)) {
            EventScreen eventScreen = (EventScreen) obj;
            if (eventScreen.getType().equals(Constant.MINE)) {
                L.d("messageevent");
                getMsgNum();
            }
            if (eventScreen.getType().equals("pic") && !TextUtils.isEmpty((String) eventScreen.getOther())) {
                L.d("messageevent");
                Glide.with(getActivity()).load(eventScreen.getOther()).dontAnimate().transform(new GlideCircleTransform(getActivity())).into(userLogo);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.user_logo)
    public void onViewClicked() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionHelper.requestPermissionsResult(requestCode, permissions, grantResults, permissionResult);
    }

    PermissionHelper.PermissionResult permissionResult = new PermissionHelper.PermissionResult() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PERMISSION_SHARE:
                    break;
            }
        }

        @Override
        public void onPermissionDenied(int requestCode, String... noPermissions) {
            switch (requestCode) {
                case PERMISSION_SHARE:
                    PermissionHelper.permissionDined(getActivity(), "您拒绝了《存储》权限，无法使用分享功能，若想继续分享，请手动开启", "您拒绝了《存储》权限，无法使用分享功能.");
                    break;
//                case PERMISSION_SHARE:
//                    String des="";
//                    for(String permission:noPermissions){
//                        if(permission.equals(Manifest.permission.CALL_PHONE)){
//                            des+="<拨打电话>";
//                        }
//                        if(permission.equals(Manifest.permission.CAMERA)){
//                            des+="<相机>";
//                        }
//                    }
//                    PermissionHelper.permissionDined(getActivity(),"您拒绝了"+des+"权限，无法正常使用此功能模块，若想继续使用，请手动开启","您拒绝了"+des+"权限，无法正常使用此功能");
//                    break;
            }
        }
    };




    /**
     * 功能统计
     *
     * @param type      类型
     * @param collectId type为0和19时collectId不为空
     * @param url       有就传
     */
    private void collect(String type, String collectId, String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        if (null != collectId) {
            map.put("collectId", collectId);
        }
        if (null != url) {
            map.put("url", url);
        }
        request(UrlUtils.COLLECT, map, true, new ResponseSuccess<NewProductData>() {
            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
            }
        });
    }

}
